package com.dmall.item.listener;

import com.dmall.item.pojo.Item;
import com.dmall.manager.service.ItemService;
import com.dmall.pojo.TbItem;
import com.dmall.pojo.TbItemDesc;
import com.sun.javafx.collections.MappingChange;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * 监听商品添加消息，生成对应的静态页面
 * @author Chen 2017/11/3
 */
public class HtmlGenListener implements MessageListener {
    @Autowired
    private ItemService itemService;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${HTML_GEN_PATH}")
    private String HTML_GEN_PATH;
    @Override
    public void onMessage(Message message) {
        try{
            //创建一个模板
            //从消息中取出商品Id
            TextMessage textMessage = (TextMessage )message;
            String text = textMessage.getText();
            Long itemId = new Long(text);
            //等待事务提交
            Thread.sleep(1000);
            //根据商品Id查询商品信息，商品基本信息和商品描述
            TbItem tbItem =itemService.getItemById(itemId);
            Item item = new Item(tbItem);
            //取出商品描述
            TbItemDesc itemDesc = itemService.getItemDescById(itemId);
            //创建一个数据集，把商品数据封装
            Map data = new HashMap<>();
            data.put("item",item);
            data.put("itemDesc",itemDesc);
            //创建一个数据集，把商品数据封装
            Configuration configuration = freeMarkerConfigurer.getConfiguration();
            Template template = configuration.getTemplate("item.ftl");
            Writer out = new FileWriter(HTML_GEN_PATH+itemId+".html");
            //生成静态页面
            template.process(data,out);
            out.close();
        }catch (Exception e){

        }
        //生成静态页面
        //关闭流
    }
}
